//
//  DDUserAccountModel.swift
//  swift微博
//
//  Created by whitcast on 16/7/12.
//  Copyright © 2016年 whitcast. All rights reserved.
//

import UIKit

class DDUserAccountModel: NSObject,NSCoding {
    //access_token
    var access_token: String?
    //	access_token的生命周期
    var expires_in: NSTimeInterval = 0 {
        
        didSet {
            //过期时间赋值
            expressedTimeOut = NSDate().dateByAddingTimeInterval(expires_in)
        }
    }
    //uid授权用户的UID
    var uid: Int = 0
    //过期时间
    var expressedTimeOut :NSDate?
    //重写description
    override var description :String {
        
        let keys = ["access_token","expires_in","uid","screen_name","profile_image_url"]
        
        return dictionaryWithValuesForKeys(keys).description
        
    }

    //用户姓名
    var screen_name :String?
    //用户头像
    var profile_image_url :String?
    
    //字典转模型
    init(dic : [String : AnyObject]) {
        super.init()

    setValuesForKeysWithDictionary(dic)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    // MARK:--归档实现的方法
    //归档
    func encodeWithCoder(aCoder: NSCoder){
        
       aCoder.encodeObject(screen_name, forKey: "screen_name")
        
        aCoder.encodeObject(profile_image_url, forKey: "profile_image_url")
        
         aCoder.encodeObject(access_token, forKey: "access_token")
        
         aCoder.encodeObject(expressedTimeOut, forKey: "expressedTimeOut")
        
    }
    //解档
   required init?(coder aDecoder: NSCoder) {
    
       profile_image_url = aDecoder.decodeObjectForKey("profile_image_url") as? String
    
       screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
    
       access_token = aDecoder.decodeObjectForKey("access_token") as? String
    
     expressedTimeOut = aDecoder.decodeObjectForKey("expressedTimeOut") as? NSDate
        
    }
    
    //类方法的存储于取出
     func storeData(model :DDUserAccountModel)->Bool {
        //归档
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.plist")
        
        return NSKeyedArchiver.archiveRootObject(model, toFile: path)
    }
    
    //解档
    class func getDataFormLocal()->DDUserAccountModel?{
         let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.plist")
        
        let model :AnyObject? = NSKeyedUnarchiver.unarchiveObjectWithFile(path)
        
        if model != nil{
        
        return (model as? DDUserAccountModel)!
            
        }else {
            
            return nil
        }
    }
}
